package com.yhh.college_information_platform.controller;

import com.yhh.college_information_platform.annotation.RequireRole;
import com.yhh.college_information_platform.common.PageResult;
import com.yhh.college_information_platform.common.Result;
import com.yhh.college_information_platform.constant.RoleConstant;
import com.yhh.college_information_platform.dto.*;
import com.yhh.college_information_platform.service.NotificationService;
import com.yhh.college_information_platform.service.ResourceService;
import com.yhh.college_information_platform.service.StatisticsService;
import com.yhh.college_information_platform.service.UserService;
import com.yhh.college_information_platform.vo.ResourceVO;
import com.yhh.college_information_platform.vo.StatisticsVO;
import com.yhh.college_information_platform.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 管理员Controller（仅管理员可访问）
 *
 * @author yhh
 * @date 2025-10-26
 */
@Slf4j
@RestController
@RequestMapping("/admin")
@RequireRole({RoleConstant.ADMIN})  // 整个Controller仅管理员可访问
public class AdminController {
    
    @Autowired
    private ResourceService resourceService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private StatisticsService statisticsService;
    
    @Autowired
    private NotificationService notificationService;
    
    // ==================== 数据统计 ====================
    
    /**
     * 获取系统统计数据
     */
    @GetMapping("/statistics")
    public Result<StatisticsVO> getStatistics(HttpServletRequest request) {
        // 验证管理员权限
        String role = (String) request.getAttribute("role");
        if (!"admin".equals(role)) {
            return Result.error(403, "无权访问");
        }
        
        StatisticsVO statistics = statisticsService.getSystemStatistics();
        return Result.success(statistics);
    }
    
    // ==================== 资料管理 ====================
    
    /**
     * 获取待审核资料列表
     */
    @PostMapping("/resources/pending")
    public Result<PageResult<ResourceVO>> getPendingResources(
            @RequestBody ResourceQueryDTO queryDTO,
            HttpServletRequest request) {
        
        // 验证管理员权限
        String role = (String) request.getAttribute("role");
        if (!"admin".equals(role)) {
            return Result.error(403, "无权访问");
        }
        
        // 设置状态为待审核
        queryDTO.setStatus(0);
        
        PageResult<ResourceVO> pageResult = resourceService.getResourcePage(queryDTO, null);
        return Result.success(pageResult);
    }
    
    /**
     * 审核资料
     */
    @PutMapping("/resources/{id}/audit")
    public Result<Void> auditResource(
            @PathVariable Long id,
            @Valid @RequestBody ResourceAuditDTO auditDTO,
            HttpServletRequest request) {
        
        // 验证管理员权限
        String role = (String) request.getAttribute("role");
        if (!"admin".equals(role)) {
            return Result.error(403, "无权访问");
        }
        
        Long userId = (Long) request.getAttribute("userId");
        resourceService.auditResource(id, auditDTO.getStatus(), auditDTO.getRejectReason(), userId);
        
        return Result.success();
    }
    
    /**
     * 删除资料（管理员）
     */
    @DeleteMapping("/resources/{id}")
    public Result<Void> deleteResourceByAdmin(
            @PathVariable Long id,
            HttpServletRequest request) {
        
        // 验证管理员权限
        String role = (String) request.getAttribute("role");
        if (!"admin".equals(role)) {
            return Result.error(403, "无权访问");
        }
        
        Long userId = (Long) request.getAttribute("userId");
        resourceService.deleteResourceByAdmin(id, userId);
        
        return Result.success();
    }
    
    // ==================== 用户管理 ====================
    
    /**
     * 获取用户列表
     */
    @PostMapping("/users")
    public Result<PageResult<UserVO>> getUserList(
            @RequestBody UserQueryDTO queryDTO,
            HttpServletRequest request) {
        
        // 验证管理员权限
        String role = (String) request.getAttribute("role");
        if (!"admin".equals(role)) {
            return Result.error(403, "无权访问");
        }
        
        PageResult<UserVO> pageResult = userService.getUserPage(queryDTO);
        return Result.success(pageResult);
    }
    
    /**
     * 更新用户信息
     */
    @PutMapping("/users/{id}")
    public Result<Void> updateUser(
            @PathVariable Long id,
            @Valid @RequestBody UserUpdateDTO updateDTO,
            HttpServletRequest request) {
        
        // 验证管理员权限
        String role = (String) request.getAttribute("role");
        if (!"admin".equals(role)) {
            return Result.error(403, "无权访问");
        }
        
        Long adminId = (Long) request.getAttribute("userId");
        userService.updateUserByAdmin(id, updateDTO, adminId);
        
        return Result.success();
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/users/{id}")
    public Result<Void> deleteUser(
            @PathVariable Long id,
            HttpServletRequest request) {
        
        // 验证管理员权限
        String role = (String) request.getAttribute("role");
        if (!"admin".equals(role)) {
            return Result.error(403, "无权访问");
        }
        
        Long adminId = (Long) request.getAttribute("userId");
        userService.deleteUserByAdmin(id, adminId);
        
        return Result.success();
    }
    
    /**
     * 重置用户密码
     */
    @PutMapping("/users/{id}/reset-password")
    public Result<String> resetPassword(
            @PathVariable Long id,
            HttpServletRequest request) {
        
        // 验证管理员权限
        String role = (String) request.getAttribute("role");
        if (!"admin".equals(role)) {
            return Result.error(403, "无权访问");
        }
        
        Long adminId = (Long) request.getAttribute("userId");
        String newPassword = userService.resetPassword(id, adminId);
        
        return Result.success("密码重置成功，新密码为：" + newPassword, newPassword);
    }
    
    // ==================== 系统通知 ====================
    
    /**
     * 发送系统通知
     */
    @PostMapping("/notification/send")
    public Result<Void> sendSystemNotification(
            @Valid @RequestBody SystemNotificationDTO dto,
            HttpServletRequest request) {
        
        // 验证管理员权限
        String role = (String) request.getAttribute("role");
        if (!"admin".equals(role)) {
            return Result.error(403, "无权访问");
        }
        
        notificationService.sendSystemNotification(
            dto.getReceiverId(),
            dto.getTitle(),
            dto.getContent()
        );
        
        String targetDesc = dto.getReceiverId() == null ? "全体用户" : "用户ID:" + dto.getReceiverId();
        log.info("管理员发送系统通知成功，目标：{}", targetDesc);
        
        return Result.success();
    }
}

